#!/usr/bin/env python

import resource.string.app

from .._console import Console

class Sms(Console):

    def run(self):
        self.greeting(resource.string.app)
        
        print 'Running...'
        
        self.farewell()
                
    def test(self):
        self.progress('Opening modem... ')
        modem = self.loadModem()
        if modem: self.success('OK ^_^v\n')
        else:
            self.fail('Error >_<\n')
            self.info('SMS test aborted.\n')
            return

        self.progress('Encoding SMS... ')
        recipient = self._args.destination
        message = ' '.join(self._args.message)[0:100]
        try:
            sms = messaging.sms.SmsSubmit(recipient, message)
            self.success('OK ^_^v\n')
        except:
            self.fail('Error >_<\n')
            self.info('SMS test aborted.\n')
            return

        pdus = sms.to_pdu()
        if len(pdus) > 1:
            self.info('\nThe message you\'re trying to send is too long.\n')
            self.info('This is just for testing purpose.\n')
            self.info('Please be reasonable ~_~\n')
            self.info('SMS test aborted.\n')
            return
        
        self.progress('Sending SMS... ')
        pdu = pdus[0]
        command = '+CMGS=%d' % pdu.length
        response = modem.attention(command)
        ok = response.find('>') >= 0
        if ok:
            command = '%s\x1a' % pdu.pdu
            response = modem.attention(command, 7, False, False)
            ok = response.find('OK') >= 0
        if ok:
            self.success('OK ^_^v\n')
        else:
            self.fail('Error >_<\n')
